package com.markhsiu.minimq.core.constant;

import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;

public class ByteUtils {

	public static boolean compare(byte[] a, byte[] b) {
		if (a == null) {
			if (b == null) {
				return true;
			}
			return false;
		}

		if (b == null) {
			return false;
		}

		int aLength = a.length;
		if (aLength != b.length) {
			return false;
		}

		for (int i = 0; i < aLength; i++) {
			if (a[i] != b[i]) {
				return false;
			}
		}

		return true;
	}

	public static byte[] newByte(int capacity) {
		return new byte[capacity];
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void cleanMappedByte(MappedByteBuffer buffer) {
		AccessController.doPrivileged(new PrivilegedAction() {
			@SuppressWarnings("restriction")
			public Object run() {
				try {
					Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
					getCleanerMethod.setAccessible(true);
					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
					cleaner.clean();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});
	}
}
